<?php

use Core\ResourceController;
use Libraries\Uploader;
use Libraries\SMS;
use Models\User;
use Models\Favorite;
use Models\Evaluate;
use Models\Product;
use Models\Withdrawals;
use Models\UserLevel;
use Models\Money_log;
use Models\Order;
use Models\Config;
use Models\Recharge;

class UserController extends ResourceController
{
	protected $scopeRequired = null;

	public function info()
	{
		$user_id = $this->session->authUser['id'];
		$user = (new User)->find($user_id);
		if(!$user['nickname']) $user['nickname'] = $user['username'];

		$user['favorites'] = Favorite::where('user_id', $user['id'])->counts();
		$user['evaluates'] = Evaluate::where('user_id', $user['id'])->counts();

		$order = new Order;
		$orders = arr_key($order->select('status, count(*) as rows')->where('user_id', $user['id'])->group_by('status')->get(), 'status');
		$orders['a'] = 0;
		$user['orders'] = $orders;
		$user['has_evaluate_order'] = $order->where('user_id', $user_id)->where('status=3 and comment=0')->counts();
		$user['song'] = Config::where('label', '充值设置')->get();

		return $this->success($user);
	}

	// 上传图片
	public function avatar()
	{
		$base64_string = $this->input->post('base64_string');
		if (!$base64_string) {
			return $this->validateError('缺少base64_string');
		}
		$result = Uploader::base64_up($base64_string, APPPATH.'uploadfiles/image/', 'png');
		if ($result) {
			$this->success([
				'avatar' => '/uploadfiles/image/'.$result
			]);
		} else {
			$this->error($this->upload->display_errors());
		}
	}

	// 保存属性
	public function save()
	{
		$post = $this->input->post();
		$user = (new User)->find($this->session->authUser['id']);

		$allows = ['username', 'nickname', 'avatar', 'sex', 'phone', 'email', 'birthday', 'pay_pass', 'old_pay_pass'];
		$set = count($post);
		foreach ($post as $key => $value) {
			if ($key == 'phone') {
				if (!SMS::verify('bindPhone', $value, $this->input->get('code'))) {
					return $this->validateError('验证码错误');
				}
				if (User::where('phone', $value)->counts()) {
					return $this->validateError('手机号已被绑定');
				}
			}

			if ($key == 'pay_pass' && $user['pay_pass'] != $this->input->post('old_pay_pass')) {
				return $this->error('旧支付密码错误');
			}

			if (in_array($key, $allows) && $key != 'old_pay_pass') {
				$user[$key] = $value;
				$set--;
			}
		}
			$user->update();
			return $this->success($user);

	}

	public function evaluates()
	{
		$evaluate = new Evaluate;
		$page = $evaluate->where('user_id', $this->session->authUser['id'])
			->order_by('create_time desc')
			->with(['product', 'item', 'user'])
			->paginate(20)
			->to_array();
		foreach ($page['data'] as $key => $value) {
			$page['data'][$key]['images'] = array_filter(explode(',', $value['images']));
		}

		return $this->success($page);
	}

	/**
	 * 获取浏览记录商品
	 */
	public function get_historys()
	{
		$id = explode(',', $this->input->get('id'));
		$product = new Product;
		$products = $product->where_in('id', $id)->get();

		return $this->success($products);
	}

	public function withdrawals()
	{
		$this->load->library('form_validation');
		$this->form_validation->set_rules('bank', '银行', 'required|integer')
		->set_rules('card_no', '银行卡号', 'required|numeric')
		->set_rules('name', '开户人姓名', 'required')
		->set_rules('mobile', '手机号码', 'required|integer')
		->set_rules('money', '体现金额', 'required|numeric');
		if ($this->form_validation->run()) {
			$user = (new User)->find($this->session->authUser['id']);
			if ($user['balance'] < $this->input->post('money')) {
				return $this->validateError('余额不足');
			}
			$withdrawals = new Withdrawals();
			$withdrawals->load($this->input->post());
			$withdrawals['user_id'] = $this->session->authUser['id'];
			$withdrawals['create_time'] = date('Y-m-d H:i:s');
			$withdrawals->add();

			$user->decrement('balane', $user['id'], $this->input->post('money'));

			return $this->success();
		} else {
			return $this->validateError($this->form_validation->error());
		}
	}

	// 用户等级
	public function levels()
	{
		$user = (new User)->find($this->session->authUser['id']);
		$userLevel = $user->level();
		$levels = (new UserLevel)->where('level >', $userLevel['level'])->order_by('level')->get();

		return $this->success([
			'user' => $user,
			'userLevel' => $userLevel,
			'levels' => $levels,
		]);
	}

	// 获取银行列表
	public function getBanks()
	{
		$banks = CONFIG('basic.banks');

		return $this->response($banks);
	}

	public function money_logs()
	{
		$money_log = new Money_log;
		if ($this->input->get('date')) {
			$money_log->where('create_time >=', strtotime($this->input->get('date')));
		}
		if ($this->input->get('type')) {
			$money_log->where('type', $this->input->get('type'));
		}
		if ($this->input->get('is_income') !== '') {
			if ($this->input->get('is_income') == 0) {
				$money_log->where('num < 0');
			} else {
				$money_log->where('num > 0');
			}
		}

		$page = $money_log
					->order_by('create_time desc')
					->paginate(20)
					->to_array();

		return $this->success($page);
	}

	public function recharge()
	{
		$this->load->library('form_validation');
		$this->form_validation->set_rules('money', '充值金额', 'required|numeric');
		if (!$this->form_validation->run()) {
			return $this->validateError('money', '输入金额不正确');
		}
		$recharge = new Recharge();
		$add = Recharge::getPresent($this->input->post('money'));
		$recharge->load([
			'user_id' => $this->session->authUser['id'],
			'money' => $this->input->post('money') + $add,
			'recharge' => $this->input->post('money'),
			'present' => $add,
			'status' => 1,
			'create_time' => date('Y-m-d H:i:s')
		]);
		$id = $recharge->add();

		return $this->success([
			'id' => $id
		]);
	}

	public function reset_pay_pass()
	{
		$this->load->library('form_validation');
		$this->form_validation->set_rules('validate', '邮箱验证码', 'required|email_validate_code[forgotValidateCode]')
			->set_rules('pay_pass', '新支付密码', 'required');
		if (!$this->form_validation->run()) {
			return $this->validateError($this->form_validation->error_array());
		}

		$user = (new User)->find($this->session->authUser['id']);
		$user['pay_pass'] = $this->input->post('pay_pass');
		$user->save();

		return $this->success();
	}
}
